type StorageType = 'localStorage' | 'sessionStorage';

class Storage {
  private storage: globalThis.Storage;

  constructor(type: StorageType = 'localStorage') {
    this.storage = type === 'localStorage' ? window.localStorage : window.sessionStorage;
  }

  set(key: string, value: any, expire?: number) {
    const data = {
      value,
      expire: expire ? new Date().getTime() + expire : null,
    };
    this.storage.setItem(key, JSON.stringify(data));
  }

  get(key: string) {
    const item = this.storage.getItem(key);
    if (!item) return null;

    const data = JSON.parse(item);
    if (data.expire && data.expire < new Date().getTime()) {
      this.storage.removeItem(key);
      return null;
    }
    return data.value;
  }

  remove(key: string) {
    this.storage.removeItem(key);
  }

  clear() {
    this.storage.clear();
  }
}

export const localStorage = new Storage('localStorage');
export const sessionStorage = new Storage('sessionStorage');